package cn.com.fuhuitong.main.home.ui.fragment

import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Bundle
import androidx.annotation.DimenRes
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.app.BASE_HTTP_URL
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeFragment
import cn.com.fuhuitong.main.cate.entity.CateChildEntity
import cn.com.fuhuitong.main.home.adapter.*
import cn.com.fuhuitong.main.home.entity.ExpressNewEntity
import cn.com.fuhuitong.main.home.entity.HomeEntity
import cn.com.fuhuitong.main.home.entity.HomeGoodsEntity
import cn.com.fuhuitong.main.home.ui.activity.HomeEnrollActivity
import cn.com.fuhuitong.main.home.vm.HomeViewModel
import cn.com.fuhuitong.main.order.ui.fragment.OrderListFragment
import cn.com.fuhuitong.utils.JsonUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.layout.*
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.TimeUtils
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.tencent.smtt.sdk.TbsVideo
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.fragment_main_home.smartRefreshLayout
import kotlinx.android.synthetic.main.fragment_order_list.*
import kotlinx.android.synthetic.main.item_home_bulletin.view.*


class HomeFragment : ViewModeFragment<HomeViewModel>() {


    private lateinit var homeSearchAdapter: HomeSearchAdapter
    private lateinit var homeBannerAdapter: HomeBannerAdapter
    private lateinit var homeCategoryAdapter: HomeCategoryAdapter

    //    private lateinit var homeBulletinAdapter: HomeBulletinAdapter
    private lateinit var homeActionImageAdapter: HomeActionImageAdapter
    private lateinit var homeTitleAdapter: HomeTitleAdapter
    private lateinit var homeGoodsAdapter: HomeGoodsAdapter

    override fun viewModel(): HomeViewModel = ViewModelProvider(
        requireActivity(),
        ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
    ).get(HomeViewModel::class.java)

    override val layoutResId: Int
        get() = R.layout.fragment_main_home

    override fun initView() {
//        swipe_refresh_home.isEnabled = false

        this.initViewRecyclerAdapter(
            recycler_home, arrayOf(
                HVT.HOME_BANNER.ordinal,
                HVT.HOME_CATEGORY.ordinal,
                HVT.HOME_GOODS.ordinal
            )
        )

        val adapters = mutableListOf<DelegateAdapter.Adapter<*>>(
            initViewHomeSearchAdapter().apply {
                homeSearchAdapter = this
            }, initViewHomeBannerAdapter().apply {
                homeBannerAdapter = this
            }, initViewHomeCategoryAdapter().apply {
                homeCategoryAdapter = this
            },
//            initViewHomeBulletinAdapter().apply {
//                homeBulletinAdapter = this
//            },
            initViewHomeActionImageAdapter().apply {
                homeActionImageAdapter = this
            }, initViewHomeTitleAdapter().apply {
                homeTitleAdapter = this
            }, initViewHomeGoodsAdapter().apply {
                homeGoodsAdapter = this
            }
        )

        delegateAdapter.addAdapters(adapters)

        homeSearchAdapter.setOnItemChildClickListener { view, i, s ->
            if (view.id == R.id.frame_home_search) {
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_SEARCH)
                    .navigation()
            }
        }

        homeBannerAdapter.setOnBannerListener { view, i, bannerEntity ->
            if (bannerEntity.url.isNullOrEmpty()) {
                if (!TbsVideo.canUseTbsPlayer(requireContext()))
                    return@setOnBannerListener
                TbsVideo.openVideo(
                    requireContext(),
                    "$BASE_HTTP_URL${bannerEntity.file}",
                    Bundle().apply {
                        putInt("screenMode", 102)
                    })
            } else {
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.UNKNOWN.apply {
                            desc = ""
                        }, data = bannerEntity.url)
                    )
                    .navigation()
            }
        }

        homeCategoryAdapter.setOnItemClickListener { view, i, homeIconEntity ->
            when (homeIconEntity.type) {
                0 -> {
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_CATEGORY)
                        .withInt(AppConstance.BUNDLE_CATEGORY_ID, homeIconEntity.id)
                        .withString(AppConstance.BUNDLE_CATEGORY_TITLE, homeIconEntity.title)
                        .navigation()
                }
                1 -> {
                    //健康大使
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MEMBER)
                        .withInt(AppConstance.BUNDLE_MEMBER_ACTION, 1)
                        .navigation()
                }
                2 -> {
                    //领取福利
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_CASE)
                        .withInt(AppConstance.BUNDLE_CASE_ACTION, 2)
                        .withString(AppConstance.BUNDLE_CASE_TITLE, homeIconEntity.title)
                        .navigation()
                }
                3 -> {
                    //家庭驿站
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MEMBER)
                        .withInt(AppConstance.BUNDLE_MEMBER_ACTION, 2)
                        .navigation()
                }
                4 -> {
                    //改善案例
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_CASE)
                        .withInt(AppConstance.BUNDLE_CASE_ACTION, 1)
                        .withString(AppConstance.BUNDLE_CASE_TITLE, homeIconEntity.title)
                        .navigation()
                }
                5 -> {
                    //旗舰店
//                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_HOME_FLAGSHIP_DETAILS)
//                        .navigation()

                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_HOME_FLAGSHIP_LIST)
                        .withInt(AppConstance.BUNDLE_CATEGORY_ID, homeIconEntity.id)
                        .navigation()
                }
                6 -> {
                    //公益慈善
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_CHARITY)
                        .navigation()
                }
                7 -> {
                    //会员权益
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MEMBER)
                        .withInt(AppConstance.BUNDLE_MEMBER_ACTION, 0)
                        .navigation()
                }
                8 -> {
                    //每日签到
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_SIGN_UP)
                        .navigation()
                }
            }
        }

        homeGoodsAdapter.setOnItemClickListener { _, _, goodsListEntity ->
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_GOODS_DETAILS)
                .withInt(AppConstance.BUNDLE_GOODS_ID, goodsListEntity.id)
                .navigation()
        }

//        homeBulletinAdapter.setOnItemChildClickListener { view, i, mutableList ->
//            if (view.id == R.id.text_home_bulletin_title) {
//                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_HOME_BULLETIN)
//                    .navigation()
//            }
//        }

        homeActionImageAdapter.setOnItemClickListener { view, i, s ->
//            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MEMBER)
//                .withInt(AppConstance.BUNDLE_MEMBER_ACTION, 1)
//                .navigation()

//            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
//                .withSerializable(
//                    AppConstance.BUNDLE_WEB_VIEW,
//                    MainBean(type = WebConfig.PUBLIC_CHARITY, data = null)
//                )
//                .navigation()

            ActivityUtils.startActivity(HomeEnrollActivity::class.java)
        }


        with(smartRefreshLayout) {
            setRefreshHeader(MaterialHeader(requireContext()))
            setRefreshFooter(ClassicsFooter(requireContext()))
        }
        smartRefreshLayout.setOnRefreshListener {
            smartRefreshLayout.finishRefresh(true)
            viewModel.homeIndex()
        }
        smartRefreshLayout.setOnLoadMoreListener {
            smartRefreshLayout.finishLoadMore(true)
            viewModel.homeGoods()
        }

    }

    override fun initData() {
        viewModel.homeIndex()
    }

    override fun initViewMode() {
        viewModel.homeDataLiveData.observe(viewLifecycleOwner, Observer { response ->

            val dataLength: Int = if (response.response?.data != null) 1 else 0

            smartRefreshLayout.isEnabled = dataLength != 0

            when (response.status) {
                HttpResponseStatus.Status.START -> {
                    if (dataLength == 0) {
                        showLoadEmptyView()
                    }
                }
                HttpResponseStatus.Status.SUCCESS -> {
                    if (dataLength == 0) {
                        showNullEmptyView(EmptyContent("重新加载", "暂无数据"))
                    } else {
                        hideEmptyView()
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    if (dataLength == 0) {
                        showErrorEmptyView(EmptyContent("重新加载", response.statusTip))
                    }
                    toast(response.statusTip)
                }
            }

            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                this.fillDataHome(it)
            }
        })

        viewModel.homeGoodsDataLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.let {
                if (it.data.list.size < 20) {
                    smartRefreshLayout.finishLoadMoreWithNoMoreData()
                }
                if (it.loadMore) {
                    homeGoodsAdapter.setAddDataMore(it.data.list)
                } else {
                    homeGoodsAdapter.setAddDataNew(it.data.list)
                }
            }
        })
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        viewModel.homeIndex()
    }

    private fun fillDataHome(entity: HomeEntity) {

        homeBannerAdapter.setAddDataNew(mutableListOf(entity.banner))
        homeCategoryAdapter.setAddDataNew(entity.home_icon)
//        homeBulletinAdapter.setAddDataNew(mutableListOf(entity.express_news))
        homeActionImageAdapter.setAddDataNew(mutableListOf(entity.chief_experience))
        homeTitleAdapter.setAddDataNew(mutableListOf("好物推荐"))

        viewModel.homeGoods(true)
    }

    /**
     * 初始化头部搜索适配器
     * */
    private fun initViewHomeSearchAdapter(): HomeSearchAdapter {
        val helper = StickyLayoutHelper(true)
        return HomeSearchAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化轮播图适配器
     * */
    private fun initViewHomeBannerAdapter(): HomeBannerAdapter {
        val helper = LinearLayoutHelper()
        helper.setPadding(
            dp2px(requireContext(), R.dimen.dp_13),
            dp2px(requireContext(), R.dimen.dp_0),
            dp2px(requireContext(), R.dimen.dp_13),
            dp2px(requireContext(), R.dimen.dp_0)
        )
        helper.bgColor = Color.WHITE
        return HomeBannerAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化分类适配器
     * */
    private fun initViewHomeCategoryAdapter(): HomeCategoryAdapter {
        val helper = GridLayoutHelper(4)
        helper.vGap = dp2px(requireContext(), R.dimen.dp_20)
        helper.hGap = dp2px(requireContext(), R.dimen.dp_5)
        helper.setPadding(
            dp2px(requireContext(), R.dimen.dp_10),
            dp2px(requireContext(), R.dimen.dp_20),
            dp2px(requireContext(), R.dimen.dp_10),
            dp2px(requireContext(), R.dimen.dp_15)
        )
        helper.setAutoExpand(false)
        helper.bgColor = Color.WHITE
        return HomeCategoryAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化快报通知适配器
     * */
    private fun initViewHomeBulletinAdapter(): HomeBulletinAdapter {
        val helper = SingleLayoutHelper()
        return HomeBulletinAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化活动图适配器
     * */
    private fun initViewHomeActionImageAdapter(): HomeActionImageAdapter {
        val helper = SingleLayoutHelper()
        return HomeActionImageAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化活动图适配器
     * */
    private fun initViewHomeTitleAdapter(): HomeTitleAdapter {
        val helper = SingleLayoutHelper()
        helper.setPadding(
            dp2px(requireContext(), R.dimen.dp_10),
            dp2px(requireContext(), R.dimen.dp_6),
            dp2px(requireContext(), R.dimen.dp_10),
            dp2px(requireContext(), R.dimen.dp_0)
        )
        return HomeTitleAdapter(
            requireContext(), helper
        )
    }

    /**
     * 初始化物品适配器
     * */
    private fun initViewHomeGoodsAdapter(): HomeGoodsAdapter {
        val helper = StaggeredGridLayoutHelper(2)
        helper.vGap = dp2px(requireContext(), R.dimen.dp_10)
        helper.hGap = dp2px(requireContext(), R.dimen.dp_13)
        helper.setPadding(
            dp2px(requireContext(), R.dimen.dp_13),
            dp2px(requireContext(), R.dimen.dp_10),
            dp2px(requireContext(), R.dimen.dp_13),
            dp2px(requireContext(), R.dimen.dp_10)
        )
        return HomeGoodsAdapter(
            requireContext(), helper
        )
    }


    companion object {
        fun dp2px(context: Context, dpValue: Float): Int {
            val scale: Float = context.resources.displayMetrics.density
            return (dpValue * scale + 0.5f).toInt()
        }

        fun dp2px(context: Context, @DimenRes id: Int): Int {
            return context.resources.getDimensionPixelSize(id)
        }

        //获取屏幕高度
        fun getScreenWidth(context: Context): Int {
            return context.resources?.displayMetrics?.widthPixels ?: 0
        }

        //获取屏幕高度
        fun getScreenHeight(context: Context): Int {
            return context.resources?.displayMetrics?.heightPixels ?: 0
        }
    }
}